import { listStore } from '../../stores/list';
import * as React from 'react';
import { observer } from 'mobx-react';
import { WeaTable, WeaLocaleProvider, WeaTag, WeaDropdown } from 'ecCom';
import { toJS, observable } from 'mobx';
import { isExitIconHandle } from './utils';
import jQuery from 'jquery';
import { Pagination, Menu, Button } from 'antd'
import _ from 'lodash';
const getLabel = WeaLocaleProvider.getLabel;
const MenuItem = Menu.Item;
const ButtonGroup = Button.Group;
export interface TreeProps {
    store: listStore;
}
@observer
export default class Tree extends React.Component<TreeProps>{


    @observable height = 0;
    render() {
        const { store } = this.props;
        const { searchTree, tableData, disquerycheck, defalutPagesize ,rowCheckKey} = store;
        const rowSelection = disquerycheck == '1' ? undefined : {
            onSelectAll(key, value) {
                store.resetTreeValueId();
                let val = "";
                if (key) {
                    store.setSelectedRowKeys(key, value);
                } else {
                    store.setSelectedRowKeys(key, []);
                }
                if (store.treeKey.length > 0) {
                    val = _.uniq(store.treeKey.map(d => d.split('_')[0])).join(",");
                }
                store.setTreeValueId(val);
            },
            onChange(key, value) {
                store.resetTreeValueId();
                store.getSelectedRowKeys();
                store.setSelectedRowKeys(key, []);
                let val = "";
                if (key) {
                    val = _.uniq(key.map(d => d.split('_')[0])).join(",");
                }
                store.setTreeValueId(val);
            },
            getCheckboxProps : record =>({
                    disabled: record.randomFieldCk === 'false',    // 配置无法勾选的列
            }),
            selectedRowKeys: store.selectedRowKeys

        };
        var pageSizeOptions = [10, 20, 30, 40, 50, 100];
        if (defalutPagesize && defalutPagesize > 0 && pageSizeOptions.indexOf(defalutPagesize) == -1) {
            pageSizeOptions.push(defalutPagesize);
            pageSizeOptions = pageSizeOptions.sort((a, b) => { return a - b });
        }
        return (
            <div>
                <WeaTable
                    className="cube-list-table"
                    columns={toJS(this.parseColumns(store.treecolumns))}
                    // getColumns={toJS(this.parseColumns(store.treecolumns))}
                    dataSource={toJS(tableData.Data)}
                    childrenColumnName="sublist"
                    rowKey="key"
                    needScroll={true}
                    rowstylefield="rowstylefield"
                    createOperateDom="createOperateDom"
                    rowSelection={rowSelection}
                    indentSize="0px"
                    renderCell={this.renderCell}
                    onOperatesClick={store.doCustomButton}
                    pagination={false}
                    onRowClick={this.onRowClick}
                    needRowClick={true}
                    rowCheckKey={rowCheckKey}
                    {...this.getScrollConfig()}
                />
                <div style={{ float: 'right', margin: '7px' }}>
                    <Pagination
                        current={searchTree.current}
                        pageSize={searchTree.pagesize}
                        pageSizeOptions={pageSizeOptions}
                        total={tableData.total}
                        showSizeChanger={true}
                        showQuickJumper={true}
                        showTotal={this.showTotal}
                        onShowSizeChange={this.onShowSizeChange}
                        onChange={store.nextDetailDatas}
                    />
                </div>
            </div>
        )
    }

    onShowSizeChange=(current, pageSize) => { 
        const { store } = this.props;
        store.changeDetailPageSize(current, pageSize) 
    }

    showTotal = (total) => {
        return ` ${getLabel(18609, "共") + total+' ' + getLabel(18256, "条")} `;
    }

    getScrollConfig() {
        const { store } = this.props;
        const { originalTableWidth } = store;
        // let widthss = jQuery(window).width() - 60;
        // let widths = 0;
        // if(treeDataWidth>100){
        //     treecolumns.map(columns=>{
        //         const{width} = columns;
        //         widths += jQuery(window).width()*0.01*parseFloat(width.replace('%', ''))*0.8;
        //     });
        // }else if(treecolumns.length > 20 && treecolumns.length < 30){
        //     widths = jQuery(window).width()+300;
        // }else if(treecolumns.length > 30&& treecolumns.length < 50){
        //     widths = jQuery(window).width()+600;
        // }
        let widths = jQuery(window).width() * (parseFloat(originalTableWidth.replace('%', '')) / 100)
        let scroll: any = {}
        let hight = jQuery(window).height();
        scroll.scroll = {}
        scroll.scroll.y = hight - 300;
        scroll.scroll.x = widths - 70;
        return scroll;
    }
    tableWidth = (_?: any) => {
        const { store } = this.props;
        return store.originalTableWidth;
    }

    componentDidMount() {
        this.getScrollConfig();
        this.parseTreeIndent();
        this.resetTableStyle(); // 重置样式
    }
    resetTableStyle = () => {
        const { tableData, addScrollForTree } = this.props.store;
        addScrollForTree(tableData.Data);
    }
    parseTreeIndent = ()=>{
            /**展示树形数据时，每层缩进后 内容左对齐“展开符号” */
        setTimeout(() => {
            const { disquerycheck } = this.props.store;
            const domArray = jQuery("span[class*='ant-table-row-indent indent-level-']")
            _.forEach(domArray, (item, index) => {
                let paddingLeft: number = item.className.split('indent-level-')[1] * 20;
                if (paddingLeft > 0) {
                    if (disquerycheck === '1') {  // 当隐藏check框时，需增大padding-left
                        paddingLeft += 28;
                    }
                    jQuery(item).parent().css('padding-left', paddingLeft);
                }
            });
        }, 1000)
    }

    componentDidUpdate(prevProps: Readonly<TreeProps>, prevState: Readonly<{}>, snapshot?: any): void {
        this.parseTreeIndent();
    }

    parserColumnsForShowList = (record, num, cb, index) => {
        const {isShowIcon} = this.props.store;
        let otherparas = cb.otherpara.split("+");
        let index1 = 0;
        for (index1; index1 < otherparas.length; index1++) {
            let islikebutton = otherparas[index1].replace("#islikebutton:", "");
            if (islikebutton && islikebutton == '1') {
                let likeinfo = otherparas[index1 + 1].replace("#likeinfo:", "")
                let type = likeinfo.split(",")[0];
                let status = likeinfo.split(",")[3];
                let likecount = likeinfo.split(",")[1];
                let dislikecount = likeinfo.split(",")[2];
                if (type == '5') {
                    if (status == '1') {
                        return <Button type="ghost" onClick={() => { this.props.store.likeOrDislike(record, "0", index, '2') }}>
                            <span>
                                <i title={getLabel('31129', '取消') + cb.text} className={"icon-coms02-like"} />
                                { isShowIcon ? <span title={cb.text || ''}>{'(' + likecount + ')'}</span>:<span>{' ' + cb.text + '(' + likecount + ')'}</span>}
                            </span></Button>
                    } else {
                        return <Button type="ghost" onClick={() => { this.props.store.likeOrDislike(record, "1", index, '2') }}>
                            <span>
                                <i title={cb.text} className={"icon-coms02-like-o"} />
                                { isShowIcon ? <span title={cb.text || ''}>{'(' + likecount + ')'}</span>:<span>{' ' + cb.text + '(' + likecount + ')'}</span>}
                            </span></Button>
                    }
                } else if (type == '6') {
                    if (status == '2') {
                        return <Button type="ghost" onClick={() => { this.props.store.likeOrDislike(record, "0", index, '2') }}>
                            <span>
                                <i title={getLabel('31129', '取消') + cb.text} className={"icon-coms02-Negative-comment"} />
                                { isShowIcon ? <span title={cb.text || ''}>{'(' + dislikecount + ')'}</span>:<span>{' ' + cb.text + ' (' + dislikecount + ')'}</span>}
                            </span></Button>
                    } else {
                        return <Button type="ghost" onClick={() => { this.props.store.likeOrDislike(record, "2", index, '2') }}>
                            <span>
                                <i title={cb.text} className={"icon-coms02-Negative-comment-o"} />
                                { isShowIcon ? <span title={cb.text || ''}>{'(' + dislikecount + ')'}</span>:<span>{' ' + cb.text + ' (' + dislikecount + ')'}</span>}
                            </span></Button>
                    }
                }
            }
        }
        return <Button title={cb.text || ''} type="ghost" onClick={() => {
            this.props.store.doCustomButton(record, '', cb, '')
        }}>
             { cb.icon ? <div title={cb.text || ''} className='cube-list-icon-box' ><img src={cb.icon} /></div> : (!isShowIcon ? '':<div className='cube-list-icon-box' ><img src={'/mobilemode/piclibrary/01-E9_default/setup.png'} /></div> )}
           {!isShowIcon ? cb.text :''}
        </Button>
    }

    parserColumnsForFunc = (record, num, cb, index, isExitIcon) => {
        let otherparas = cb.otherpara.split("+");
        let index1 = 0;
        for (index1; index1 < otherparas.length; index1++) {
            let islikebutton = otherparas[index1].replace("#islikebutton:", "");
            if (islikebutton && islikebutton == '1') {
                let likeinfo = otherparas[index1 + 1].replace("#likeinfo:", "")
                let likecount = likeinfo.split(",")[1];
                let dislikecount = likeinfo.split(",")[2];
                let type = likeinfo.split(",")[0];
                let status = likeinfo.split(",")[3];
                if (type == '5') {
                    if (status == '1') {
                        return <MenuItem>
                            <span
                                onClick={() => {
                                    this.props.store.likeOrDislike(record, "0", index, '2')
                                }}
                            >
                                <span><i title={getLabel('31129', '取消') + cb.text} className={"icon-coms02-like"} /><span style={{ color: '#000' }}>{' ' + cb.text + '(' + likecount + ')'}</span></span>
                            </span>
                        </MenuItem>;
                    } else {
                        return <MenuItem>
                            <span
                                onClick={() => {
                                    this.props.store.likeOrDislike(record, "1", index, '2');
                                }}
                            >
                                <span><i title={cb.text} className={"icon-coms02-like-o"} /><span style={{ color: '#000' }}>{' ' + cb.text + ' (' + likecount + ')'}</span></span>
                            </span>
                        </MenuItem>;
                    }
                } else if (type == '6') {
                    if (status == '2') {
                        return <MenuItem>
                            <span
                                onClick={() => {
                                    this.props.store.likeOrDislike(record, "0", index, '2');
                                }}
                            >
                                <span><i title={getLabel('31129', '取消') + cb.text} className={"icon-coms02-Negative-comment"} /><span style={{ color: '#000' }}>{' ' + cb.text + ' (' + dislikecount + ')'}</span></span>
                            </span>
                        </MenuItem>;
                    } else {
                        return <MenuItem>
                            <span
                                onClick={() => {
                                    this.props.store.likeOrDislike(record, "2", index, '2');
                                }}
                            >
                                <span><i title={cb.text} className={"icon-coms02-Negative-comment-o"} /><span style={{ color: '#000' }}>{' ' + cb.text + ' (' + dislikecount + ')'}</span></span>
                            </span>
                        </MenuItem>;
                    }
                }
            }
        }
        return <MenuItem>
            <span
                onClick={() => {
                    this.props.store.doCustomButton(record, '', cb, '')
                }}
            >
                { isExitIcon ? <div className='cube-list-icon-box' >{cb.icon ? <img src={cb.icon} />:''}</div> : ''}
                <span style={{ color: '#000' }}>{cb.text}</span>
            </span>
        </MenuItem>;
    }

    parseColumns = (columns) => {
        const { store } = this.props;
        const { treePercent,isSuspend ,isShowIcon, showButtomNum} = store;
        const cols = columns.map((col, index) => ({
            title: col.title,
            className: col.className,
            isHtml: false,
            key: col.key,
            dataIndex: col.dataIndex,
            width: ((parseFloat(col.width.replace('%', '')) / treePercent) * 100).toFixed(2) + '%',
            render: (text, record, index) => {
                if (col.dataIndex == 'cube_expandmap') {
                    let valueSpan: any = record[col.dataIndex + "span"] !== undefined ? record[col.dataIndex + "span"] : record[col.dataIndex];
                    let num = -1;
                    let classname: any = col.className == 'column-text-right' ? 'right' : col.className == 'column-text-center' ? 'center' : 'left';
                    if (record.randomfieldid && record.randomfieldid != '') {
                        record['randomFieldId'] = record.randomfieldid;
                    }
                    let count = valueSpan && JSON.parse(valueSpan).length;
                    let custombutton;
                    let custombuttonArray;
                    if (count > showButtomNum  && !isShowIcon) {
                        if(showButtomNum>0){
                            let valueSpanarrry = JSON.parse(valueSpan).slice(0, showButtomNum);
                            let valueSpanTemp = JSON.parse(valueSpan).slice(showButtomNum-1);
                            const isExitIcon = isExitIconHandle('opt', valueSpanTemp);
                            custombuttonArray = valueSpanTemp && valueSpanTemp.map(cb => {
                                return this.parserColumnsForFunc(record, num, cb, index, isExitIcon);
                            });
                            custombutton = valueSpanarrry && valueSpanarrry.map(cb => {
                                num++;
                                if (num < showButtomNum-1) {
                                    return this.parserColumnsForShowList(record, num, cb, index);
                                } else if (num == showButtomNum-1) {
                                    return (
                                        <WeaDropdown
                                            className='wea-table-page-more-drop-down'
                                            getPopupContainer={() => document.getElementById("buttonGroupbtn"+index+record['randomFieldId'])}
                                            overlay={
                                                <Menu>
                                                    {custombuttonArray}
                                                </Menu>
                                            }>
                                            {getLabel(17499, "更多")}
                                        </WeaDropdown>
                                    );
                                }
                            });
                        }else{
                            let valueSpanTemp = JSON.parse(valueSpan).slice(0);
                            const isExitIcon = isExitIconHandle('opt', valueSpanTemp);
                            custombuttonArray = valueSpanTemp && valueSpanTemp.map(cb => {
                                return this.parserColumnsForFunc(record, num, cb, index, isExitIcon);
                            });
                            return <div>
                                    <div id={"buttonGroupbtn"+index+record['randomFieldId']} className={`cube-list-table-cusoperate ${isSuspend? 'cusoperate-hidden':"cusoperate-visible"}`} style={{ textAlign: classname, whiteSpace: 'normal' }}>
                                        <ButtonGroup>
                                            <WeaDropdown
                                                className='wea-table-page-more-drop-down'
                                                getPopupContainer={() => document.getElementById("buttonGroupbtn"+index+record['randomFieldId'])}
                                                overlay={
                                                    <Menu>
                                                        {custombuttonArray}
                                                    </Menu>
                                                }>
                                                {getLabel(17499, "更多")}
                                            </WeaDropdown>
                                        </ButtonGroup>
                                    </div>
                                </div>
                        }

                        return <div>
                            <div id={"buttonGroupbtn"+index+record['randomFieldId']} className={`cube-list-table-cusoperate ${isSuspend? 'cusoperate-hidden':"cusoperate-visible"}`} style={{ textAlign: classname, whiteSpace: 'normal' }}>
                                <ButtonGroup>{custombutton}</ButtonGroup>

                            </div>
                        </div>
                    } else {
                        custombutton = valueSpan && JSON.parse(valueSpan).map(cb => {
                            num++;
                            return this.parserColumnsForShowList(record, num, cb, index);
                        });
                        return <div  className={isShowIcon ? 'cube-list-table-cusoperate-onlyicon':'cube-list-table-cusoperate-andicon'}>
                            <div className={`cube-list-table-cusoperate ${isSuspend? 'cusoperate-hidden':"cusoperate-visible"}`} style={{ textAlign: classname, whiteSpace: 'normal' }}>
                                <ButtonGroup>{custombutton}</ButtonGroup>
                            </div>
                        </div>
                    }
                } else {
                    return <span dangerouslySetInnerHTML={{ __html: text }} />;
                }
            }
        }))
        return cols;
    }

    renderCell = (columns) => {
        //let biaoqian  = <div className={"e8operate"}  style={{display: 'block'}}>&nbsp;</div>;
        return columns.map((col) => {
            if (col.dataIndex == 'modelableid') { //如果是标签
                let newColumn = col;
                let classname: any = col.className == 'column-text-right' ? 'right' : col.className == 'column-text-center' ? 'center' : 'left';
                newColumn.render = (text, record, index) => { //前端元素转义
                    let valueSpan = record[newColumn.dataIndex + "span"] !== undefined ? record[newColumn.dataIndex + "span"] : record[newColumn.dataIndex];
                    let weatag = valueSpan && JSON.parse(valueSpan).map(tag => {
                        if (tag.tabname != '') {
                            return <WeaTag title={tag.tabname} style={{ borderRadius: '4px', marginBottom: 2, marginRight: 10, color: tag.color, backgroundColor: tag.bgcolor, borderColor: tag.bdcolor }}>
                                {tag.tabname.length > 10 ? `${tag.tabname.slice(0, 10)}...` : tag.tabname}
                            </WeaTag>
                        } else {
                            return tag + " ";
                        }
                    });
                    return <div><div style={{ textAlign: classname, whiteSpace: 'normal' }}>{weatag}</div></div>
                }
                return newColumn;
            }
            return col;
        });
    }

    onRowClick = (record, index) =>{
        const {update} = this.props.store;
        update({rowCheckKey:[record.key || record.id]})
    }
}
